# encoding = utf-8
import time
import tkinter
import psutil
import os
from os.path import join, getsize
from apscheduler.schedulers.background import BackgroundScheduler
from socket import *


def getProcessMemory(pid):
    process = psutil.Process(pid)
    memInfo = process.memory_full_info()
    return memInfo.uss / 1024 / 1000

def getPocessTotalMem(process_name):
    totalM = 0
    for i in psutil.process_iter():
        if i.name() == process_name:
            totalM += getProcessMemory(i.pid)
    return totalM

def calculateMem(process_names):
    memInfo = {}
    for process_name in process_names:
        mem_used = str('%.2f' % getPocessTotalMem(process_name)) + 'MB'
        memInfo[process_name] = mem_used
    return memInfo

def getdirsize(dire):
    size = 0
    for root, dirs, files in os.walk(dire):
        size += sum([getsize(join(root, name)) for name in files])
    return size

def writeEmail(meminfo, dirpath):
    import time
    with open('outputMessage.txt', 'w') as f:
        fields = '{0:15}      {1:30}'.format("进程名", "内存占用")
        print(fields, file=f)
        [print('{0:20}     {1:30}'.format(key, meminfo[key]), file=f) for key in meminfo.keys()]
        dirsize = getdirsize(dirpath)
        print('\n软件目录大小：     ', end='', file=f)
        print(str('%.2f' % float(dirsize / 1024 / 1024)) + 'MB', file=f)
        localt = time.localtime(time.time())
        time = time.strftime('%Y-%m-%d %H:%M:%S', localt)
        print('数据采集时间：     ' + str(time), file=f)

scheduler = BackgroundScheduler(timezone='Asia/Shanghai')

@scheduler.scheduled_job("cron", hour=9, minute=0)
def sendInfoToServer():
    pass

def connectServer():
    address = '127.0.0.1'  # 服务器的ip地址
    port = 40012  # 服务器的端口号
    buffsize = 1024  # 接收数据的缓存大小
    serv = socket(AF_INET, SOCK_STREAM)
    serv.connect((address, port))
    with open('outputMessage.txt', 'w+') as f:
        message = f.read()
        f.truncate()
    senddata = message
    if senddata == '':
        serv.close()
    else:
        serv.send(senddata.encode())
        recvdata = serv.recv(buffsize).decode('utf-8')
        print(recvdata)
        serv.close()

if __name__ == '__main__':
    process_names = ['KGService.exe', 'KuGou.exe', 'Clover.exe']
    dirpath = "D:\迅雷下载"
    info = calculateMem(process_names)
    writeEmail(info, dirpath)
    try:
        # connectServer()
        scheduler.start()
        while True:
            time.sleep(8)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
        print("程序退出成功！")
